
import os
import re
import fnmatch
import glob 
from pathlib import Path


# Replace 'directory_path' with the path to the directory you want to search
#d_directory_path = '../download_dir/pastnotes1982/WEB/HTML'
#u_directory_path = '../upload_dir/pastnotes1982/WEB/HTML'

d_htm_directory_path = './download_dir/pastnotes1982/WEB/HTML/'
u_htm_directory_path = './download_dir/pastnotes1982/WEB/HTML/'
u_vid_directory_path = './download_dir/pastnotes1982/WEB/videos/'
final_directory_path = '../videos/'

newtext_hls = """
<head>
  <link href="../js/video-js.min.css" rel="stylesheet">
  <script src="../js/video.min.js"></script>
</head>
<body>
<!--
source_url = %s
videoid = %s
-->

<video
    id="my-player"
    class="video-js"
    controls
    preload="auto"
    width="320" height="240"
    data-setup='{}'>
    <source src="%s" type="application/x-mpegURL">
    <p class="vjs-no-js"> please enable JavaScript  </p>
</video>
</body>
"""


# Define the regular expression pattern
pattern1 = re.compile(r'Mirrored.{200}', re.DOTALL)
pattern2 = re.compile(r'BLOGGER-video-[\d\w-]*', re.DOTALL)
    


def version_two():
  
  Path(u_htm_directory_path).mkdir(parents=True, exist_ok=True)
  
  # Loop through each file in the directory
  for filename in os.listdir(d_htm_directory_path):
    # Check if the file extension is .htm
    if fnmatch.fnmatch(filename, 'VIDEO*.HTM'):
      #if filename.endswith('.HTM'):
      # Open the file and read its contents
      with open(os.path.join(d_htm_directory_path, filename), 'r') as file:
        contents = file.read()
        if pattern1.search(contents):
          res1 = pattern1.search(contents).group(0)
          res2 = pattern2.search(contents).group(0)
                
          uvfilename = u_vid_directory_path + res2 + ".m3u8"

          if os.path.exists(uvfilename):
            final_file_path = final_directory_path + res2 + ".m3u8"
            print (final_file_path)
            newcontents = (newtext_hls % (res1, res2, final_file_path))            
            with open(os.path.join(u_htm_directory_path, filename), 'w') as new_file:
              new_file.write(newcontents)
              print(f"{filename} updated")
          else:
            print(f"{filename} failed to find corresponding m3u8")


version_two()

